class Admin::NguoiDungController < ApplicationController
  include ApplicationHelper
  def index
    @trang = (params[:page].present? && params[:page].to_i > 1 ?  params[:page] : 1).to_i
    if (params[:cap_nhat].present?)
      params[:nguoi_dung].each { |k, v|
        nguoi  = NguoiDung.find(k)
        if (nguoi.present?)
          nguoi.is_nhan_vien = nguoi['is_nhan_vien'].present? || nguoi['is_xu_ly_don_hang'].present?
          nguoi.is_xu_ly_don_hang = nguoi['is_xu_ly_don_hang'].present?
        end
      }
    end
    
    if ['nhan_vien', 'khach_hang'].include?(params[:loc])
      if params[:loc] == 'nhan_vien'
        query = NguoiDung.where(:is_admin => false, :dang_kich_hoat => true, :is_nhan_vien => true)
      else
        query = NguoiDung.where(:is_admin => false, :dang_kich_hoat => true, :is_nhan_vien => false)
      end
    else
      query = NguoiDung.where(:is_admin => false, :dang_kich_hoat => true)
    end
    @nguoi_dungs = query.paginate(
      :order => :ten_hien_thi.asc,
      :per_page => 20,
      :page => params[:page]
    )
    @co_trang_sau = !query.paginate(
      :order => :ten_hien_thi.asc,
      :per_page => 20,
      :page => @trang + 1
    ).empty?
    @co_trang_truoc = @trang > 1
    @index_dau_tien = (@trang - 1) * 20

  end

  def cap_nhat
  end

  def xoa
    nguoi_dung = nguoi_dung_hien_tai()
    if nguoi_dung.present? && nguoi_dung.is_admin && params[:uid].present?
      nguoi_can_xoa = NguoiDung.find(params[:uid])
      if (nguoi_can_xoa.present?)
      nguoi_can_xoa.dang_kich_hoat = false;
      nguoi_can_xoa.save
      end
    end
    redirect_to :back
  end

  def tao_moi
    if (params[:commit])
      nguoi_dung = NguoiDung.find_by_email(params[:email])
      if (nguoi_dung.present? && !nguoi_dung.dang_kich_hoat)
        nguoi_dung.dang_kich_hoat = true
        nguoi_dung.ten_hien_thi = params[:ten_hien_thi]
        nguoi_dung.is_xu_ly_don_hang = params[:is_xu_ly_don_hang].present?
        nguoi_dung.is_nhan_vien = false
        nguoi_dung.save
      else
        nguoi_dung = NguoiDung.create({
          :ten_hien_thi => params[:ten_hien_thi],
          :email => params[:email],
          :mat_khau => "x" * 6,
          :mat_khau_confirmation => "x" * 6,
          :is_xu_ly_don_hang => params[:is_xu_ly_don_hang].present?,
          :is_nhan_vien => true,
          :is_admin => false
        })
      end

      if (nguoi_dung.present?)
        flash.now[:thanh_cong] = t('them_nhan_vien_thanh_cong')
      else
        flash.now[:loi] = t('vui_long_xem_lai_cac_thong_tin')
      end
      
      NguoiDung.quen_mat_khau(params[:email], @hostname)
    end
  end
end
